<template>
  <div>
    <el-drawer
      class="custom-drawer"
      :append-to-body="true"
      size="100%"
      title="编辑图片"
      :visible="open"
      @close="handleClose"
      :with-header="false"
    >
      <div class="drawer_header">
        <div class="close_box">
          <div @click="handleClose" class="close_bg">
            <i class="el-icon-close"></i>
          </div>
        </div>
      </div>
      <div class="canvas-box">
        <canvas ref="canvas" class="canvas" :class="{'canvas-crosshair':drawingMode}"></canvas>
        <div class="btns">
          <i @click="toggleDrawingMode(false)" class="el-icon-rank"></i>
          <div class="rela">
            <img class="brn_icon" @click="toggleDrawingMode(true)" src="@/assets/images/imageEditer/pen.png" alt="加载失败">
            <div class="absolute" :class="{'flex':drawingMode}">
              <div class="slider">
                <el-slider
                  :show-tooltip="false"
                  :step="5"
                  v-model="sliderWidth"
                  height="200px">
                </el-slider>
              </div>
              <span> {{sliderWidth}}</span>
            </div>
          </div>
          <img class="brn_icon" @click="toggleEraserMode" src="@/assets/images/imageEditer/eraser.png" alt="加载失败">
          <img class="brn_icon" @click="addText" src="@/assets/images/imageEditer/text.png" alt="加载失败">
          <el-color-picker
            v-model="drawingColor"
            show-alpha
            size="mini"
            :predefine="predefineColors"
          >
          </el-color-picker>
          <i @click="deleteSelected" class="el-icon-delete-solid"></i>
          <img class="brn_icon" @click="saveImage" src="@/assets/images/imageEditer/save.png" alt="加载失败">
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import { fabric } from 'fabric'
import { uploadOSS } from "@/api/upload";

export default {
  props: {
    imageUrl: {
      type: String,
      default: 'https://oss.metaxun.com/cloud/7/course/22b89a2c-cdf6-4ba5-8f02-decd48f15396/ex@mFile/1726728686454.jpg'
    },
    open: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      sliderWidth:10,
      drawingColor: 'rgba(255, 69, 0, 0.68)',
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ],
      canvas: null,
      image: null,
      drawingMode: false,
      eraserMode: false,
      text: '这里是文字'
    }
  },
  created() {

  },
  watch: {
    sliderWidth(val){
      this.canvas.freeDrawingBrush.width = this.sliderWidth
    },
    drawingColor() {
      this.changeColor()
    },
    open(e) {
      if (e){
        this.$nextTick(() => {
          // 清理之前的 Canvas 实例和事件监听器
          this.clearCanvasAndEvents()
          this.canvas = new fabric.Canvas(this.$refs.canvas, {
            isDrawingMode: this.drawingMode
          })
          this.handleFileChange()
          // 设置 Canvas 尺寸
          this.canvas.setWidth(800)
          this.canvas.setHeight(500)
          // 监听键盘事件
          document.addEventListener('keydown', this.handleKeyDown)
          // 监听鼠标滚轮事件
          document.addEventListener('wheel', this.handleWheel)
        })
      }
    }
  },
  beforeDestroy() {
    document.removeEventListener('keydown', this.handleKeyDown)
    document.removeEventListener('wheel', this.handleWheel)
  },
  methods: {
    clearCanvasAndEvents() {
      if (this.canvas) {
        this.canvas.dispose() // 清理 Canvas 实例
        this.canvas = null
      }
      // 移除事件监听器
      document.removeEventListener('keydown', this.handleKeyDown)
      document.removeEventListener('wheel', this.handleWheel)
    },
    handleClose() {
      this.$emit('update:open', false)
    },
    changeColor(){
      this.canvas.freeDrawingBrush.color = this.drawingColor
    },
    handleFileChange() {
      if (this.imageUrl) {
        const imgObj = new Image()
        imgObj.crossOrigin = 'Anonymous' // 设置跨域属性
        imgObj.src = this.imageUrl
        imgObj.onload = () => {
          const targetWidth = 800 // 设置目标宽度为800
          const targetHeight = 500 // 设置目标高度为500
          const imgWidth = imgObj.width
          const imgHeight = imgObj.height
          let scaleFactor
          if (imgWidth >= imgHeight) {
            // 根据宽高比例确定缩放比例
            scaleFactor = targetWidth / imgWidth
          } else {
            // 根据宽高比例确定缩放比例
            scaleFactor = targetHeight / imgHeight
          }
          const scaledWidth = imgWidth * scaleFactor
          const scaledHeight = imgHeight * scaleFactor
          this.image = new fabric.Image(imgObj, {
            editable: true,
            selectable: false,
            left: (this.canvas.width - scaledWidth) / 2, // 水平居中
            top: (this.canvas.height - scaledHeight) / 2 // 垂直居中
          })
          this.image.scaleToWidth(scaledWidth)
          this.image.scaleToHeight(scaledHeight)
          this.canvas.add(this.image)
          this.image.sendToBack()
        }
      }
    },
    sendImageToBack() {
      const image = this.canvas.getActiveObject() // 获取当前选中的对象，即上传的图片
      if (image) {
        image.sendToBack() // 将图片发送到最底层
        this.canvas.renderAll() // 重新渲染画布
      }
    },
    toggleDrawingMode(bol) {
      this.drawingMode = bol
      this.canvas.isDrawingMode = this.drawingMode
      if (bol) {
        this.canvas.freeDrawingBrush.color = this.drawingColor
        this.canvas.freeDrawingBrush.width = this.sliderWidth
      }
      this.eraserMode = false // 关闭橡皮擦模式
    },
    handleWheel(event) {
      if (!this.drawingMode){
        return
      }
      // 根据滚轮滚动的方向调整画笔粗细
      if (event.deltaY > 0) {
        if (this.sliderWidth>0){
          this.sliderWidth -= 5  // 减小画笔粗细
        }
      } else {
        if (this.sliderWidth<100){
          this.sliderWidth += 5 // 增加画笔粗细
        }
      }
      this.canvas.freeDrawingBrush.width = this.sliderWidth
      // 确保画笔粗细不小于最小值
      this.canvas.freeDrawingBrush.width = Math.max(1, this.canvas.freeDrawingBrush.width)
    },
    toggleEraserMode() {

    },
    addText() {
      this.drawingMode = false
      this.canvas.isDrawingMode = this.drawingMode
      const text = new fabric.Textbox(this.text, {
        left: 50,
        top: 50,
        fill: this.drawingColor
      })
      this.canvas.add(text)
    },
    async saveImage() {
      // 获取 Canvas 的 base64 数据
      let imageData = this.$refs.canvas.toDataURL('image/png')
      // 将base64数据转换为Blob对象
      let blob = this.base64ToBlob(imageData)
      // 创建文件对象
      let file = new File([blob], 'editor_image.png', { type: 'image/png' })
      let res = await uploadOSS(file);
      this.$emit('saveEditorImage', res[0])
    },
    base64ToBlob(base64) {
      let byteCharacters = atob(base64.split(',')[1])
      let byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      let byteArray = new Uint8Array(byteNumbers)
      return new Blob([byteArray], { type: 'image/png' })
    },
    deleteSelected() {
      const activeObjects = this.canvas.getActiveObjects()
      if (activeObjects && activeObjects.length > 0) {
        activeObjects.forEach(obj => {
          this.canvas.remove(obj)
        })
      }
    },
    handleKeyDown(event) {
      if (event.key === 'Delete') {
        this.deleteSelected()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.canvas-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .canvas {
    border: 2px solid #a8a8a8;
  }

  .btns {
    margin-top: 20px;
    width: 800px;
    height: 40px;
    background: rgba(0, 0, 0, 0.8);
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: space-around;

    .brn_icon {
      width: 20px;
      height: 20px;
      object-fit: cover;
      cursor: pointer;
    }
    .absolute{
      position: absolute;
      bottom: -50px;
      display: none;
      align-items: center;
      .slider{
        width: 100px;
      }
      span{
        font-size: 12px;
        margin-left: 8px;
        color: #28b28b;
      }
    }

    i {
      color: #ffffff;
      font-size: 20px;
      cursor: pointer;
    }
  }
}
.canvas-crosshair {
  cursor: crosshair;
}
.drawer_header {
  width: 100%;
  display: flex;
  padding: 20px;
  box-sizing: border-box;
  justify-content: center;
  .close_box{
    width: 920px;
    display: flex;
    justify-content: flex-end;
    .close_bg{
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: #66676b;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      .el-icon-close {
        font-size: 24px;
        color: #ffffff;
      }
    }
  }
}
.custom-drawer{
  //z-index: 3001!important;
}
.flex{
  display: flex!important;
}
</style>
